package client.comm.commlib.widget

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.core.view.children
import androidx.fragment.app.FragmentActivity
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import client.comm.commlib.R
import com.google.android.material.bottomnavigation.BottomNavigationView

class InitNavHost @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    val contentId: Int

    @Volatile
    var isInit = false

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.homeNavStyle)
        contentId = typedArray.getResourceId(R.styleable.homeNavStyle_content_id, -1)
        isInit = false
        typedArray.recycle()
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        if (!isInit) {
            isInit = true
            for ((i, child) in children.withIndex()) {
                if (i == 0)
                    child.isSelected = true
                child.setOnClickListener {
                    if (it.isSelected)
                        return@setOnClickListener

                    val controller =
                        ((context as FragmentActivity).supportFragmentManager.findFragmentById(
                            contentId
                        ) as NavHostFragment).navController

                    if (!controller.popBackStack(it.id, false)) {
                        controller.navigate(
                            it.id,
                            null,
                            NavOptions.Builder().setPopUpTo(it.id, false).setLaunchSingleTop(true)
                                .build()
                        )
                    }

                    for (v in children) {
                        if (v == it) {
                            v.isSelected = true
                        } else {
                            v.isSelected = false
                        }
                    }
                }
            }
        }

    }
}